package com.momo.mal.manga.view;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.lang3.text.WordUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.actionbarsherlock.view.SubMenu;
import net.momo.mal.R;
import com.momo.mal.database.MalDatabaseAdapter;
import com.momo.mal.entity.Manga;
import com.momo.mal.entity.Related;
import com.momo.mal.util.ConnectionUtil;
import com.momo.mal.util.DialogSearch;
import com.momo.mal.util.MangaUtil;
import com.viewpagerindicator.PageIndicator;
import com.viewpagerindicator.TitlePageIndicator;

public class MangaView extends SherlockActivity {
	private MangaViewAdapter adapter;
	private ViewPager pager;
	private PageIndicator indicator;
	private String[] params;
	private MalDatabaseAdapter dbAdapter;
	private Manga manga = new Manga();
	private String mangaId, title;
	private ImageView imageManga;
	private ProgressBar progressBar;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.manga_view);

		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		if (getIntent().hasExtra("title")) {
			title = getIntent().getStringExtra("title") + " - Manga";
			mangaId = getIntent().getStringExtra("manga_id") + "";
			params = new String[] { getIntent().getStringExtra("manga_id"),
					getIntent().getStringExtra("title") };
		} else {
			title = getIntent().getData().getQueryParameter("title")
					+ " - Manga";
			mangaId = getIntent().getData().getQueryParameter("anime_id") + "";
			params = new String[] {
					getIntent().getData().getQueryParameter("manga_id"),
					getIntent().getData().getQueryParameter("title") };
		}

		setTitle(title);

		imageManga = (ImageView) findViewById(R.id.image_manga);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);

		dbAdapter = new MalDatabaseAdapter(this);

		new RequestMangaView(this).execute(params);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Resources res = getResources();
		SubMenu subMainMenu = menu.addSubMenu("Menu");
		subMainMenu.add(res.getString(R.string.menu_search))
				.setIcon(R.drawable.ic_menu_search)
				.setOnMenuItemClickListener(new OnMenuItemClickListener() {

					@Override
					public boolean onMenuItemClick(MenuItem item) {
						new DialogSearch().newInstance("manga").show(
								getSupportFragmentManager(), null);
						return false;
					}
				});
		subMainMenu.add(res.getString(R.string.menu_refresh))
				.setIcon(R.drawable.ic_menu_refresh)
				.setOnMenuItemClickListener(new OnMenuItemClickListener() {

					@Override
					public boolean onMenuItemClick(MenuItem item) {
						new RequestMangaView(MangaView.this).execute(params);
						return false;
					}
				});
		subMainMenu.add(res.getString(R.string.menu_share))
				.setIcon(R.drawable.ic_menu_share)
				.setOnMenuItemClickListener(new OnMenuItemClickListener() {

					@Override
					public boolean onMenuItemClick(MenuItem item) {
						Intent intent = new Intent(Intent.ACTION_SEND);
						intent.setType("text/plain");
						String text = "This is recommend for you. You should try "
								+ params[1]
								+ ".<br><br> <a href=\"http://myanimelist.net/manga/"
								+ params[0]
								+ "\">http://myanimelist.net/anime/"
								+ params[0] + "</a>";
						intent.putExtra(Intent.EXTRA_SUBJECT,
								"Recommend from your friend");
						intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(text));
						intent.putExtra(Intent.EXTRA_TITLE, "Momo MAL - "
								+ params[1]);

						startActivity(Intent.createChooser(intent,
								"Share Via ..."));
						return false;
					}
				});

		if (dbAdapter.hasManga(params[0]) == false) {
			subMainMenu.add(res.getString(R.string.menu_add))
					.setIcon(R.drawable.ic_menu_add)
					.setOnMenuItemClickListener(new OnMenuItemClickListener() {

						@Override
						public boolean onMenuItemClick(MenuItem item) {
							MangaUtil.mangaAddOrUpdatePopUp(manga,
									MangaView.this);
							return false;
						}
					});
		} else {
			subMainMenu.add(res.getString(R.string.menu_edit))
					.setIcon(R.drawable.ic_menu_edit)
					.setOnMenuItemClickListener(new OnMenuItemClickListener() {

						@Override
						public boolean onMenuItemClick(MenuItem item) {
							MangaUtil.mangaAddOrUpdatePopUp(
									dbAdapter.getMangaById(mangaId),
									MangaView.this);
							return false;
						}
					});
		}

		MenuItem subMenu1Item = subMainMenu.getItem();
		subMenu1Item.setIcon(R.drawable.ic_menu_more);
		subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS
				| MenuItem.SHOW_AS_ACTION_WITH_TEXT);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			finish();
		}

		return super.onMenuItemSelected(featureId, item);
	}

	private class RequestMangaView extends AsyncTask<String, Void, JSONObject> {
		private ProgressDialog dialog;
		private Context context;

		public RequestMangaView(Context context) {
			dialog = new ProgressDialog(context);

			this.context = context;
		}

		@Override
		protected JSONObject doInBackground(String... params) {
			JSONObject json = new JSONObject();
			try {
				if (dbAdapter.hasManga(params[0]) == true) {
					if (dbAdapter.isMangaSync(params[0]) == false) {
						json = ConnectionUtil.get(
								ConnectionUtil.SECONDATY_API_HOST + "manga/"
										+ params[0], context);
						json.put("sync", "true");
						json.put("manga_id", params[0]);

						Manga manga = MangaUtil.parsingMangaFromJson(json);
						dbAdapter.updateMangaSync(manga);
					} else {
						json = new JSONObject();
						json.put("sync", "true");
						json.put("manga_id", params[0]);
						json.put("title", dbAdapter.getMangaById(params[0])
								.getTitle());
					}
				} else {
					json = ConnectionUtil.get(ConnectionUtil.SECONDATY_API_HOST
							+ "manga/" + params[0], context);
				}
			} catch (JSONException e) {
				json = null;
				e.printStackTrace();
			} catch (IOException e) {
				json = null;
				e.printStackTrace();
			}

			return json;
		}

		@Override
		protected void onPostExecute(JSONObject result) {
			dialog.dismiss();
			try {
				if (result == null) {
					Toast.makeText(
							context,
							getResources().getString(R.string.failed_load_data),
							Toast.LENGTH_LONG).show();
				} else {
//					Manga manga = new Manga();
					try {
						if (result.has("sync") == true) {
							manga = dbAdapter.getMangaById(result
									.getString("manga_id"));
						} else {
							manga = MangaUtil.parsingMangaFromJson(result);
						}
						
						mangaInformation(manga);
						new RequestImage(context).execute(result);
					} catch (JSONException e) {
						e.printStackTrace();
					}

				}
			} catch (Exception e) {
				Toast.makeText(context,
						getResources().getString(R.string.failed_load_data),
						Toast.LENGTH_LONG).show();
				e.printStackTrace();
			}
		}

		@Override
		protected void onPreExecute() {
			dialog.setMessage("Loading Data ...");
			dialog.show();
		}

	}

	private class RequestImage extends AsyncTask<JSONObject, Void, Bitmap> {

		private Context context;
		
		public RequestImage(Context context) {
			this.context = context;
			progressBar.setVisibility(ProgressBar.VISIBLE);
		}

		@Override
		protected Bitmap doInBackground(JSONObject... params) {
			URL url = null;
			Drawable drawable = null;
			Bitmap bitmap = null;
			try {
				if (params[0].has("sync") == true) {
					Manga manga = dbAdapter.getMangaById(params[0]
							.getString("manga_id"));

					String state = Environment.getExternalStorageState();
					File mediaStorageDir = null;

					if (Environment.MEDIA_MOUNTED.equals(state)) {
						mediaStorageDir = new File(context
								.getExternalCacheDir(), "");
					} else if (Environment.MEDIA_MOUNTED_READ_ONLY
							.equals(state)) {
						mediaStorageDir = new File(context.getCacheDir(),
								"");
					} else {
						mediaStorageDir = new File(context.getCacheDir(),
								"");
					}

					File mediaFile = new File(mediaStorageDir.getPath()
							+ File.separator + "manga_" + manga.getId());
					bitmap = BitmapFactory.decodeFile(mediaFile
							.getAbsolutePath());
				} else {
					url = new URL(params[0].getString("image_url"));
					Object content = url.getContent();
					InputStream stream = (InputStream) content;
					// drawable = Drawable.createFromStream(stream, "src");\
					bitmap = BitmapFactory.decodeStream(stream);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			return bitmap;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			imageManga.setImageBitmap(result);
			progressBar.setVisibility(ProgressBar.GONE);
		}

	}

	private void mangaInformation(Manga manga) {
		TextView synopsys = (TextView) findViewById(R.id.text_synopsis);

		TextView type = (TextView) findViewById(R.id.text_type);
		TextView chapter = (TextView) findViewById(R.id.text_chapters);
		TextView volumes = (TextView) findViewById(R.id.text_volumes);
		TextView status = (TextView) findViewById(R.id.text_status);
		TextView genre = (TextView) findViewById(R.id.text_genre);
		TextView memberScore = (TextView) findViewById(R.id.text_member_score);
		TextView rank = (TextView) findViewById(R.id.text_rank);
		TextView popularity = (TextView) findViewById(R.id.text_popularity);
		TextView memberCount = (TextView) findViewById(R.id.text_member_count);
		TextView favorite = (TextView) findViewById(R.id.text_favorite);
		TextView english = (TextView) findViewById(R.id.text_english);
		TextView synonyms = (TextView) findViewById(R.id.text_synonyms);
		TextView japanese = (TextView) findViewById(R.id.text_japanese);
		TextView animeAdaptation = (TextView) findViewById(R.id.text_adaptation);
		TextView relatedManga = (TextView) findViewById(R.id.text_related_manga);
		TextView alternative = (TextView) findViewById(R.id.text_alternative);
		TextView score = (TextView) findViewById(R.id.text_score);
		TextView volumesRead = (TextView) findViewById(R.id.text_volumes_read);
		TextView chaptersRead = (TextView) findViewById(R.id.text_chpaters_read);
		TextView statusRead = (TextView) findViewById(R.id.text_status_read);
		TextView priority = (TextView) findViewById(R.id.text_priority);

		TextView titleAlternativeTitle = (TextView) findViewById(R.id.title_alternative_title);
		TextView titleRelatedManga = (TextView) findViewById(R.id.title_related_manga);
		TextView titleMyInfo = (TextView) findViewById(R.id.title_my_info);

		synopsys.setText(Html.fromHtml(manga.getSynopsis() + ""));
		
		type.setText("Type : " + manga.getType());
		chapter.setText("Chapters : " + manga.getChapters());
		volumes.setText("Volumes : " + manga.getVolumes());
		status.setText("Status : " + WordUtils.capitalize(manga.getStatus()));
		genre.setText("Genres : " + manga.getGenres());
		memberScore.setText("Member Score : " + manga.getMemberScore());
		rank.setText("Rank : #" + manga.getRank());
		popularity.setText("Popularity : #" + manga.getPopularityRank());
		memberCount.setText("Members : " + manga.getMemberCount());
		favorite.setText("Favourites : " + manga.getFavoriteCount());

		if (manga.getStatusSync() != null) {
			volumesRead.setText("Volumes seen : " + manga.getVolumesRead()
					+ " / " + manga.getVolumes());
			chaptersRead.setText("Chapters seen : " + manga.getChapterRead()
					+ " / " + manga.getChapters());
			statusRead.setText("Read status : "
					+ MangaUtil.parsingReadStatusView(manga.getReadStatus()));
			if (manga.getScore().equals("10"))
				score.setText("Score : " + manga.getScore() + " - Masterpiece");
			else if (manga.getScore().equals("9"))
				score.setText("Score : " + manga.getScore() + " - Great");
			else if (manga.getScore().equals("8"))
				score.setText("Score : " + manga.getScore() + " - Very Good");
			else if (manga.getScore().equals("7"))
				score.setText("Score : " + manga.getScore() + " - Good");
			else if (manga.getScore().equals("6"))
				score.setText("Score : " + manga.getScore() + " - Fine");
			else if (manga.getScore().equals("5"))
				score.setText("Score : " + manga.getScore() + " - Average");
			else if (manga.getScore().equals("4"))
				score.setText("Score : " + manga.getScore() + " - Bad");
			else if (manga.getScore().equals("3"))
				score.setText("Score : " + manga.getScore() + " - Very Bad");
			else if (manga.getScore().equals("2"))
				score.setText("Score : " + manga.getScore() + " - Horrible");
			else if (manga.getScore().equals("1"))
				score.setText("Score : " + manga.getScore() + " - Appalling");
			else
				score.setText("Score : -");
			
			if(manga.getPriority() == null) {
				priority.setText(Html.fromHtml("Priority : <font color='green'>Low</font>"));
			}
			if(manga.getPriority().equals("0")) {
				priority.setText(Html.fromHtml("Priority : <font color='green'>Low</font>"));
			}
			if(manga.getPriority().equals("1")) {
				priority.setText(Html.fromHtml("Priority : <font color='yellow'>Medium</font>"));
			}
			if(manga.getPriority().equals("2")) {
				priority.setText(Html.fromHtml("Priority : <font color='red'>High</font>"));
			}
		} else {
			volumesRead.setVisibility(TextView.GONE);
			chaptersRead.setVisibility(TextView.GONE);
			score.setVisibility(TextView.GONE);
			statusRead.setVisibility(TextView.GONE);
			titleMyInfo.setVisibility(TextView.GONE);
			priority.setVisibility(TextView.GONE);
		}

		if (manga.getEnglish().length() == 0) {
			english.setVisibility(TextView.GONE);
		}
		if (manga.getJapanese().length() == 0) {
			japanese.setVisibility(TextView.GONE);
		}
		if (manga.getSynonyms().length() == 0) {
			synonyms.setVisibility(TextView.GONE);
		}
		if (english.getVisibility() == TextView.GONE
				&& synonyms.getVisibility() == TextView.GONE
				&& japanese.getVisibility() == TextView.GONE) {
			titleAlternativeTitle.setVisibility(TextView.GONE);
		}
		english.setText("English : " + manga.getEnglish());
		japanese.setText("Japanese : " + manga.getJapanese());
		synonyms.setText("Synonyms : " + manga.getSynonyms());

		if (manga.getAnimeAdaptation().length() == 0) {
			animeAdaptation.setVisibility(TextView.GONE);
		}
		if (manga.getRelatedManga().length() == 0) {
			relatedManga.setVisibility(TextView.GONE);
		}
		if (manga.getAlternative().length() == 0) {
			alternative.setVisibility(TextView.GONE);
		}
		if (animeAdaptation.getVisibility() == TextView.GONE
				&& relatedManga.getVisibility() == TextView.GONE
				&& alternative.getVisibility() == TextView.GONE) {
			titleRelatedManga.setVisibility(TextView.GONE);
		}

		String adapt = "Adaptation : ", related = "Related : ", alternatives = "Alternative : ";
		int intAdapt = 0, intRelated = 0, intAlternatives = 0;
		for (Related r : manga.getRelated()) {
			if (r.getType().equalsIgnoreCase("adaptations")) {
				if (intAdapt == 0) {
					adapt = adapt + "<a href=\"anime://view?anime_id="
							+ r.getRelatedId() + "&title=" + r.getTitle()
							+ "\">" + r.getTitle() + "</a>";
				} else {
					adapt = adapt + ", <a href=\"anime://view?anime_id="
							+ r.getRelatedId() + "&title=" + r.getTitle()
							+ "\">" + r.getTitle() + "</a>";
				}

				intAdapt++;
			}

			if (r.getType().equalsIgnoreCase("related_manga")) {
				if (intRelated == 0) {
					related = related + "<a href=\"manga://view?manga_id="
							+ r.getRelatedId() + "&title=" + r.getTitle()
							+ "\">" + r.getTitle() + "</a>";
				} else {
					related = related + ", <a href=\"manga://view?manga_id="
							+ r.getRelatedId() + "&title=" + r.getTitle()
							+ "\">" + r.getTitle() + "</a>";
				}

				intRelated++;
			}

			if (r.getType().equalsIgnoreCase("alternative_versions")) {
				if (intAlternatives == 0) {
					alternatives = alternatives
							+ "<a href=\"manga://view?manga_id="
							+ r.getRelatedId() + "&title=" + r.getTitle()
							+ "\">" + r.getTitle() + "</a>";
				} else {
					alternatives = alternatives
							+ ", <a href=\"manga://view?manga_id="
							+ r.getRelatedId() + "&title=" + r.getTitle()
							+ "\">" + r.getTitle() + "</a>";
				}

				intAlternatives++;
			}
		}

		animeAdaptation.setText(Html.fromHtml(adapt.toString()));
		animeAdaptation.setMovementMethod(LinkMovementMethod.getInstance());

		relatedManga.setText(Html.fromHtml(related.toString()));
		relatedManga.setMovementMethod(LinkMovementMethod.getInstance());

		alternative.setText(Html.fromHtml(alternatives.toString()));
		alternative.setMovementMethod(LinkMovementMethod.getInstance());

	}

}
